<script
  lang="ts"
  setup
>
import dayjs from '#build/dayjs.imports.mjs'
import { getSurveyInfo } from '@/api/survey'
import { useResizeObserver } from '@vueuse/core'
import { scanLogin } from '~/api/login'
import { adminUrl } from '~/api/useHttp'

const route = useRoute()
const activeNav = computed(() => route.path || '/')
const navList = [
  {
    name: '首页',
    path: '/',
  },
  {
    name: '专家库',
    path: '/peopleHealth/ExpertList',
  },
  {
    name: '头条资讯',
    path: '/peopleHealth/topNews',
  },
  {
    name: '健康陕西',
    path: '/peopleHealth/healthyShaanxi',
  },
  {
    name: '百姓健康系列栏目',
    path: '/peopleHealth/peopleHealthSeries',
  },
  {
    name: '健康知识',
    path: '/peopleHealth/knowledge',
  },
  {
    name: '科普资料',
    path: '/peopleHealth/popularization',
  },
  {
    name: '宣传活动',
    path: '/peopleHealth/HealthActivity',
  },
  {
    name: '中医健康科普',
    // path: 'http://139.196.111.15:9102/health/#/pages/knowledge/knowledge',
    path: '/peopleHealth/outKnowledge',
    external: false,
  },
  {
    name: '健康评测',
    // path: 'http://139.196.111.15:9102/health/#/pages/evaluation/evaluation',
    // path: '/peopleHealth/survey',
    path: '/peopleHealth/evaluation',
    external: false,
  },
]

const menuHamburgerActive = ref(false)
const navName = computed(() => route.meta?.navName)
function isActive(item: any) {
  return item.path === activeNav.value || (item.path !== '/' && activeNav.value.indexOf(item.path) === 0) || navName.value === item.name
}
const { isBigCharMode } = storeToRefs(useGlobalStore())
const store = useUserStore()
const userInfo = computed(() => store.userInfo)
function showLogin() {
  const config = useRuntimeConfig()
  if (config.public?.env === 'dev') {
    // store.setLoginVisible(true)
    store.loginVisible = true
  }
  else {
    let currentHref = window.location.href
    if (currentHref?.includes('www') === false) {
      currentHref = `${window.location.protocol}//www.${window.location.host}${window.location.pathname}`
    }
    window.location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=wx20f0e24c8f73a8d7&redirect_uri=${encodeURIComponent(currentHref)}&response_type=code&scope=snsapi_login&state=#wechat_redirect`
  }
}

function toChatRobot() {
  navigateTo('http://139.196.111.15:8080/ui/chat/a8f8ddf4ca1385ba', {
  // navigateTo('http://139.196.111.15:8080/ui/chat/926302390298f20a', {
    external: true,
    open: {
      target: '_blank',
    },
  })
}

function toActive() {
  navigateTo('/peopleHealth/HealthActivity?classify_name=健康辟谣')
}

const surveyInfo = ref<any>()
function toSurvey() {
  const activity_no = '20240624105711000001'
  const url = `${adminUrl}/health/#/questionnaire/survey/survey?formType=form&activity_no=${activity_no}&status=进行中`
  navigateTo({
    path: '/peopleHealth/survey',
    query: {
      // webUrl: url,
      title: '满意度调查',
      from: 'home',
      webUrl: encodeURIComponent(url),
    },
  })
  // navigateTo({
  //   path: '/peopleHealth/questSurvey',
  //   query: {
  //     no: activity_no,
  //   },
  // })
}

const showSurvey = ref(false)
async function getSurveyActivity(activeNo: string) {
  const condition = [
    {
      colName: 'start_time',
      ruleType: 'le',
      value: dayjs(new Date().getTime()).format('YYYY-MM-DD'),
    },
    {
      colName: 'end_time',
      ruleType: 'ge',
      value: dayjs(new Date().getTime()).format('YYYY-MM-DD'),
    },
  ]
  const data = await getSurveyInfo(activeNo, { condition })
  return data
}
onMounted(() => {
  getSurveyActivity('20240624105711000001').then((res) => {
    if (Array.isArray(res) && res.length > 0) {
      surveyInfo.value = res[0]
      showSurvey.value = true
    }
  })
})

const showRobot = ref(true)
const showActive = ref(true)
function logout() {
  ElMessageBox.confirm('确定退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      store.logout()
    })
    .catch(() => { })
}
const links = computed(() => navList.slice(0, isBigCharMode.value ? 8 : 10))
const moreNav = computed(() => navList.slice(isBigCharMode.value ? 8 : 10))
onMounted(() => {
  const { isLogin } = useUserStore()
  if (isLogin === true) {
    store.getCollectArticleList()
  }
})

const contentRef = ref<HTMLElement | null>(null)
const parentRef = ref<HTMLElement | null>(null)
const isOverflowed = ref(false)
function checkOverflow() {
  if (contentRef.value && parentRef.value) {
    console.log(contentRef.value.scrollHeight, parentRef.value.clientHeight)
    isOverflowed.value = contentRef.value.scrollHeight > parentRef.value.clientHeight
  }
}
useResizeObserver(parentRef, (entries) => {
  checkOverflow()
})
const { wxLogin } = useUserStore()
onMounted(() => {
  if (route.query.code) {
    // 登录
    return wxLogin(route.query.code, route.query.state)
  }
  checkOverflow()
})
</script>

<template>
  <div class="pos-sticky top-0 z-1000 h-60px w-full bg-#FFF px-20px pb-2px shadow-md xl:px-80px">
    <div class="pos-relative mx-a flex items-center justify-center">
      <NuxtLink to="/" class="logo-icon mr-55px hidden w-245px xl:block" />
      <nav ref="parentRef" class="menu-box pos-relative flex flex-1 items-center justify-between">
        <div
          ref="contentRef" class="z-2 max-h-60px w-full bg-#FFF p-x-10px"
          :class="{ 'overflow-hidden': !menuHamburgerActive }"
        >
          <div class="bg-#fff">
            <NuxtLink
              v-for="nav in navList" :key="nav.name" :to="nav.path" :external="nav.external || false"
              :target="nav.external ? '_blank' : ''" class="nav-item pos-relative mx-10px px-10px"
              :class="{ 'active': isActive(nav), 'b-b-1px b-b-solid b-b-#ccc': menuHamburgerActive }"
            >
              <span class="nav-name">
                {{ nav.name }}
              </span>
            </NuxtLink>
          </div>
        </div>
      </nav>
      <button
        v-if="isOverflowed" class="reset-btn menu-hamburger m-15px w-20px cursor-pointer"
        flex="~ col justify-center" aria-label="导航" aria-expanded="false" aria-controls="full-screen"
        :class="{ active: menuHamburgerActive }" @click="menuHamburgerActive = !menuHamburgerActive"
      >
        <span class="hamburger-1" />
        <span class="hamburger-2" />
        <span class="hamburger-3" />
      </button>
      <div min-w-80px>
        <div v-if="userInfo?.user_no" flex="~ items-center justify-end">
          <!-- <span class="cursor-pointer" @click="logout">
            {{ userInfo?.user_disp || userInfo?.user_no }}
          </span> -->
          <!-- <span class="mx-5px">|</span>
          <NuxtLink class="" to="/im" target="_blank">
            咨询
          </NuxtLink> -->
          <el-dropdown :hide-on-click="false" trigger="click">
            <button class="outline-none">
              {{ userInfo?.user_disp || userInfo?.user_no }}
            </button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <NuxtLink to="/peopleHealth/myFavorite" class="h-full hover:text-#0E9472">
                    我的收藏
                  </NuxtLink>
                </el-dropdown-item>
                <el-dropdown-item @click="logout">
                  <span class="inline-block h-full hover:text-#0E9472">
                    退出登录
                  </span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <button v-else class="btn" @click="showLogin">
          登录
        </button>
      </div>
    </div>
    <Login />
    <BigCharToggle
      class="bigCharToggle transition-all duration-300"
      :class="activeNav === '/' ? 'translate-x-0' : 'translate-x-100%'"
    />
    <div v-if="activeNav === '/' && showActive" class="float-button3 hidden md:block" @click="toActive">
      <div class="close-button" @click.stop="showActive = false">
        x
      </div>
    </div>
    <div v-if="activeNav === '/' && showRobot" class="float-button hidden md:block" @click="toChatRobot">
      <div class="close-button" @click.stop="showRobot = false">
        x
      </div>
    </div>
    <div v-if="activeNav === '/' && showSurvey" class="float-button2 hidden md:block" @click="toSurvey">
      <div class="close-button" @click.stop="showSurvey = false">
        x
      </div>
    </div>
  </div>
</template>

<style
  lang="scss"
  scoped
>
.logo-icon {
  width: 351px;
  height: 50px;
  background: url('/img/logo.png');
  cursor: pointer;
}

.menu-box {
  transition: all 0.3s ease;
  transform: translateY(0);

  .nav-item {
    cursor: pointer;
    border-bottom: 4px solid transparent;
    line-height: 55px;
    font-size: var(--base-font-size);
    transition: font-size 0.3s ease-in-out;
    display: inline-block;

    &:hover {
      // border-bottom-color: var(--color-primary);
      color: var(--color-primary);

      .nav-item-children {
        display: flex;
        max-height: 100px;
      }
    }

    &.active {
      font-weight: 700;
      color: var(--color-primary);
      border-bottom-color: var(--color-primary);
    }

    .nav-item-children {
      max-height: 0;
      overflow: hidden;
      transform: translateY(100%);
      width: 200%;
      flex-direction: column;
      border: 1px solid #eee;
      border-top-color: transparent;
      color: #000;
      transition: all 0.5s ease;

      a {
        line-height: 50px;
        padding-left: 10px;
        padding-right: 10px;

        &:hover {
          color: var(--color-primary);
          background-color: #e9f7fc;
        }
      }

      @media (max-width: 768px) {
        width: 100%;
      }
    }
  }

  @media (max-width: 768px) {
    .md\:flex,
    [md\:flex=''] {
      display: flex;
    }

    &.active {
      position: absolute;
      bottom: 0;
      display: flex;
      flex-direction: column;
      width: 100%;
      transform: translateY(calc(100% - 0px));
      height: unset;

      .nav-item {
        border: none;
        line-height: 40px;
      }
    }
  }
}

button.reset-btn {
  background: none;
  border: none;
  padding: 0;
  touch-action: manipulation;
  z-index: 1;
}

.menu-hamburger {
  --text-color: #303133;
  --transition-all: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

  span {
    background-color: var(--text-color);
    border-radius: 10px;
    height: 2px;
    margin: 2px 0;
    transition: var(--transition-all);
    width: 100%;
  }

  transform: rotate(180deg);

  .hamburger-1 {
    width: 50%;
  }

  .hamburger-3 {
    width: 75%;
  }

  &.active {
    .hamburger-3 {
      transform-origin: bottom;
      width: 50%;
      transform: translate(2px, -10px) rotate(45deg);
    }

    .hamburger-2 {
      transform-origin: top;
      transform: rotate(-45deg);
    }

    .hamburger-1 {
      transform-origin: bottom;
      transform: rotate(45deg) translate(13px);
    }
  }
}

.float-button,
.float-button2,
.float-button3 {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 99999;
  background-size: 100%;
  background-image: url('/img/doctor.png');
  /*        width: 196px;
            height: 136px; */
  width: 98px;
  height: 68px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.float-button2 {
  background-image: url('/img/wjdc.png');
  bottom: 200px;
}
.float-button3 {
  background-image: url('/img/jkpy.jpg');
  bottom: 500px;
}

.close-button {
  display: none;
  position: absolute;
  top: -20px;
  right: -20px;
  font-size: 24px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  line-height: 30px;
  z-index: 99999999;
  text-align: center;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  /* font-weight: bold; */
}

.float-button:hover .close-button,
.float-button2:hover .close-button,
.float-button3:hover .close-button {
  display: unset;
}

.float-button2 .close-button {
  top: -10px;
  right: -10px;
}

@media screen and (min-width: 600px) {
  .float-button,
  .float-button2,
  .float-button3 {
    width: 196px;
    height: 136px;
    right: 60px;
    bottom: 300px;
  }

  .float-button2 {
    bottom: 100px;
    height: 180px;
    background-repeat: no-repeat;
  }
  .float-button3 {
    bottom: 470px;
    width: 196px;
    height: 136px;
    background-repeat: no-repeat;
    border-radius: 20px;
    overflow: hidden;
  }
}
</style>
